import bluetoothManager from '../../utils/bluetooth.js'
import gaiaManager from '../../utils/gaiaManager.js'

Page({
  data: {
    textRevData: '',
    scrollIntoView: 'scroll-view-bottom',
    deviceInfo: { name:'-', model:'-', version:'-', serial:'-', address:'-' },
    supportedFeatures: []
  },

  onLoad() {
    this.refreshDeviceInfo()
    this.setupDataListener()
  },

  onShow() {
    this.refreshDeviceInfo()
  },

  // 刷新设备信息
  async refreshDeviceInfo() {
    try {
      const [summary, features] = await Promise.all([
        gaiaManager.getDeviceSummary?.(),
        gaiaManager.getSupportedFeatures?.()
      ])
      if(summary) { 
        this.setData({ 
          deviceInfo: Object.assign({ name:'-', model:'-', version:'-', serial:'-', address:'-' }, summary) 
        }) 
      }
      if(Array.isArray(features)) { 
        this.setData({ supportedFeatures: features }) 
      }
    } catch(e) { 
      console.warn('加载设备信息失败', e) 
    }
  },

  // 设置数据监听
  setupDataListener() {
    bluetoothManager.setOnDataReceived((text, hex) => {
      this.addReceivedData(text, hex)
    })
  },

  // 添加接收数据
  addReceivedData(text, hex) {
    const timestamp = this.dateFormat('[hh:mm:ss,S]:', new Date())
    const data = this.data.textRevData + timestamp + (this.isCheckRevHex ? hex.replace(/[0-9a-fA-F]{2}/g, ' $&') : text) + '\r\n'
    
    this.setData({ textRevData: data })
    
    if (this.isCheckScroll) {
      if (this.data.scrollIntoView === "scroll-view-bottom") {
        this.setData({ scrollIntoView: "scroll-view-bottom2" })
      } else {
        this.setData({ scrollIntoView: "scroll-view-bottom" })
      }
    }
  },

  // 清空接收数据
  btClearTap() {
    this.setData({ textRevData: '' })
  },

  // 发送数据
  async btSendTap() {
    if (this.isCheckSendHex) {
      let data = this.sendData
        .replace(/\s*/g, '')
        .replace(/\n/g, '')
        .replace(/\r/g, '')
      
      if (data.length === 0) {
        wx.showModal({
          title: '提示',
          content: '请输入要发送的数据'
        })
        return
      }
      if (data.length % 2 != 0) {
        wx.showModal({
          title: '提示',
          content: '数据长度只能是双数'
        })
        return
      }
      if (data.length > 488) {
        wx.showModal({
          title: '提示',
          content: '最多只能发送244字节'
        })
        return
      }
      if (!new RegExp('^[0-9a-fA-F]*$').test(data)) {
        wx.showModal({
          title: '提示',
          content: '数据格式错误，只能是0-9,a-f,A-F'
        })
        return
      }
      
      const success = await bluetoothManager.writeData(data, true)
      if (success) {
        wx.showToast({
          title: '发送成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        })
      }
    } else {
      if (this.sendData.length === 0) {
        wx.showModal({
          title: '提示',
          content: '请输入要发送的数据'
        })
        return
      }
      let tempSendData = this.sendData.replace(/\n/g, '\r\n')
      if (tempSendData.length > 244) {
        wx.showModal({
          title: '提示',
          content: '最多只能发送244字节'
        })
        return
      }
      
      const success = await bluetoothManager.writeData(tempSendData, false)
      if (success) {
        wx.showToast({
          title: '发送成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        })
      }
    }
  },

  // 输入发送数据
  inputSendData(e) {
    this.sendData = e.detail.value
  },

  // 检查滚动
  checkScroll(e) {
    this.isCheckScroll = e.detail.value.length > 0
  },

  // 检查接收Hex
  checkRevHex(e) {
    this.isCheckRevHex = e.detail.value.length > 0
  },

  // 检查发送Hex
  checkSendHex(e) {
    this.isCheckSendHex = e.detail.value.length > 0
  },

  // 检查字符编码
  checkChinese(e) {
    if(e.detail.value === 'gbk') {
      bluetoothManager.setChineseType('gbk')
    } else {
      bluetoothManager.setChineseType('utf8')
    }
  },

  // 日期格式化
  dateFormat(fmt, date) {
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    }
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? (o[k] + '').padStart(3, '0')
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    return fmt
  }
})
